#include "type.h"
#include "stddef.h"
#include "mmu.h"

#include "string.h"

void*
memset(void* dst, byte_t c, size_t size) {
    byte_t* temp = (byte_t*)dst;
    for (int i = 0; i < size; i++)
        temp[i] = c;

    return dst;
}

void*
memmove(void* dst, void* src, size_t size) {
    byte_t* d = dst;
    byte_t* s = src;
    while (size > 0) {
        *d++ = *s++;
        size--;
    }
    return dst;
}

void*
memcpy(void* dst, const void* src, size_t n) {
    const char* s = (char*)src;
    char* d = (char*)dst;
    while (n > 0) {
        *d = *s;
        ++d, ++s;
        --n;
    }
    return dst;
}

int
strncmp(const char* s1, const char* s2, uint32_t len) {
    uint32_t i = 0;
    while ((s1[i] != '\0') && (i < len - 1) && (s1[i] == s2[i]))
        ++i;
    return (int)(s1[i] - s2[i]);
}

int
strcmp(const char* s1, const char* s2) {
    while (*s1 && *s1 == *s2)
        ++s1, ++s2;
    return (int)(*s1 - *s2);
}

char*
strcpy(char* dst, const char* src) {
    char* p = dst;
    while (*src != '\0') {
        *p = *src;
        ++p;
        ++src;
    }
    *p = '\0';
    return dst;
}

char*
strncpy(char* dst, const char* src, uint32_t len) {
    while (len > 0 && *src) {
        *dst = *src;
        ++src;
        ++dst;
        --len;
    }
    while (len > 0) {
        *dst = '\0';
        ++dst;
        --len;
    }
    return dst;
}

char*
strchr(const char* s, char c) {
    for (; *s; ++s)
        if (*s == c)
            return (char*)s;
    return NULL;
}

size_t
strlen(const char* s) {
    size_t cnt = 0;
    while (*s)
        ++cnt, ++s;
    return cnt;
}

char*
strdup(const char* src) {
    size_t len = strlen(src);
    char* dst = kmalloc(len + 1);
    if (dst) {
        memcpy(dst, src, len);
        dst[len] = '\0';
    }
    return dst;
}